<template>
  <el-card shadow="never" class="rd-8 mb-8">
    <el-form label-width="120px">
      <el-form-item label="信息描述">
        <el-tag type="info">excel模版说明</el-tag>
        <el-tag>
          <i class="el-icon-download" />
          <a :href="'/template.xls'">点击下载模版</a>
        </el-tag>
      </el-form-item>
      <el-form-item label="选择Excel">
        <div class="f-c-c">
          <el-upload
            v-model:file-list="fileList"
            ref="uploadRef"
            :auto-upload="false"
            :on-success="fileUploadSuccess"
            :on-error="fileUploadError"
            :on-change="handleChange"
            :limit="1"
            drag
            :action="`${BASE_API}/catalog/addByExcel`"
            accept="application/vnd.ms-excel"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              Drop file here or
              <em>click to upload</em>
            </div>

            <template #tip>
              <div class="el-upload__tip text-red">
                limit 1 file, new file will cover the old file
              </div>
            </template>
          </el-upload>
          <el-button
            :loading="loading"
            class="ml-15"
            type="success"
            :disabled="fileList.length == 0"
            @click="submitUpload"
          >
            上传到服务器
          </el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
let loading = ref(false)
const uploadRef = ref()
const BASE_API = import.meta.env.VITE_SERVE
let fileList = ref([])

const submitUpload = () => {
  loading.value = true
  uploadRef.value.submit()
}
const handleChange = (uploadFile, uploadFiles) => {
  if (!/\.(xlsx|xls|XLSX|XLS)$/.test(uploadFile.name)) {
    ElMessage.error('上传文件只能为excel文件，且为xlsx,xls格式')
    fileList.value = []
  }
}
const fileUploadSuccess = () => {
  loading.value = false
  ElMessage.success('上传成功')
  uploadRef.value.clearFiles()
}
const fileUploadError = () => {
  loading.value = false
  ElMessage.success('网络原因，上传失败')
}
</script>

<style lang="scss" scoped></style>
